import urllib

import cv2
from django.conf import settings
from django.http import HttpResponse, JsonResponse
# 表单
from django.views.decorators.csrf import csrf_exempt
import os

from FirstAIFace.pca_svm import reg_res
import datetime
import numpy as np
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, ALL_COMPLETED,as_completed
import time


def read_image(stream=None, url=None):
    if url is not None:
        response = urllib.request.urlopen(url)
        data_temp = response.read()

    elif stream is not None:
        data_temp = stream.read()

    image = np.asarray(bytearray(data_temp), dtype="uint8")
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image


def saveImage(f):
    rootPath = os.path.join(settings.MEDIA_ROOT, datetime.datetime.now().strftime('%Y-%m-%d'))
    if not os.path.exists(rootPath):
        os.makedirs(rootPath, 0o666)
    # filepath = os.path.join(rootPath,f.name)
    filepath = os.path.join(rootPath, datetime.datetime.now().strftime('%H-%M-%S-%f') + ".jpg")
    print(filepath)
    with open(filepath, 'wb') as fp:
        for info in f.chunks():
            fp.write(info)
        fp.close()


def imageReg(image_to_read):
    try:
        start = datetime.datetime.now()
        number = reg_res(image_to_read)
        # os.remove(filepath)
        end = datetime.datetime.now()
        print(end - start, flush=True)
        return number
    except IOError as err:
        print("recall error:{}".format(err), flush=True)
        return ""


# 在不同端口上还能启动
@csrf_exempt
def faceReg(request):
    if request.FILES.get("image", None) is None:  # 请求中包含图像则以流形式读取图像
        return JsonResponse("")
    f = request.FILES['image']
    image_to_read = read_image(stream=f)
    with ThreadPoolExecutor(max_workers=2) as t:
        # 线程保存图片
        task1 = t.submit(saveImage,f)#,参数
        # 图像识别服务
        task2 = t.submit(imageReg,image_to_read)
        all_task = [task1, task2]
        for future in as_completed(all_task):
            if future == task2:
                number = future.result()
    return HttpResponse(number)
